package io.renren.modules.answer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.JsonUtils;
import io.renren.common.utils.PageInput;
import io.renren.common.utils.PageUtils;
import io.renren.modules.answer.dto.input.QuestionAnswerInput;
import io.renren.modules.answer.dto.input.TopicInput;
import io.renren.modules.answer.dto.output.Message;
import io.renren.modules.answer.dto.output.OptionTwo;
import io.renren.modules.answer.dto.output.Score;
import io.renren.modules.answer.entity.Answer;
import io.renren.modules.answer.mapper.AnswerMapper;
import io.renren.modules.answer.service.ExamService;
import io.renren.modules.question.entity.QuestionMessage;
import io.renren.modules.question.mapper.QuestionMessageMapper;
import io.renren.modules.score.dao.ScoreDao;
import io.renren.modules.score.entity.ScoreEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author liangbaigao
 * @Date 2022/10/7 21:44
 */
@Service
public class ExamImpl implements ExamService {

    @Resource
    private AnswerMapper answerMapper;

    @Resource
    private ScoreDao scoreDao;

    @Resource
    private QuestionMessageMapper questionMessageMapper;

    /**
     * 问卷提交
     * @param user
     * @param questionAnswerInput
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQuestion(SysUserEntity user, QuestionAnswerInput questionAnswerInput) {
        // 校验
        QuestionMessage questionMessage
                = questionMessageMapper.selectById(questionAnswerInput.getQuestionId());
        if(ObjectUtil.isNull(questionMessage)){
            throw new RuntimeException("试卷已失效");
        }
        // 校验用户是否答卷
        QueryWrapper<Answer> queryWrapper
                = new QueryWrapper<>();
        queryWrapper.lambda().eq(Answer::getUserId,user.getUserId()).
                eq(Answer::getQuestionId,questionAnswerInput.getQuestionId());
        List<Answer> questionMessageList =
                answerMapper.selectList(queryWrapper);
        if(questionMessageList.size() != 0){
            throw new RuntimeException("请勿重复答卷");
        }
        // 填写问卷对象
        Answer answer = new Answer();
        ScoreEntity scoreEntity = new ScoreEntity();

        // Answer表入库
        answer.setUserId(user.getUserId());
        answer.setQuestionId(questionAnswerInput.getQuestionId());
        // 转json
        answer.setAnswerDetail(JsonUtils.objectToJson(questionAnswerInput));
        answerMapper.insert(answer);
        // Score表入库
        scoreEntity.setQuestionId(questionAnswerInput.getQuestionId());
        scoreEntity.setResponse(user.getUsername());
        scoreEntity.setUserid(Math.toIntExact(user.getUserId()));
        scoreEntity.setAnswerId(answer.getId());
        // 算总分
        double totalScore = 0F;
        for (TopicInput questionTopic : questionAnswerInput.getQuestionTopics()) {
         // 累加
            for (OptionTwo optionTwo : questionTopic.getOption()) {
                if(optionTwo.getIsChecked().equals("1")){
                    totalScore += optionTwo.getOptionScore();
                }
            }
        }
        scoreEntity.setScore(totalScore);
        scoreEntity.setCreatTime(new Date());
        scoreDao.insert(scoreEntity);
    }

    /**
     * 查看已发布的试卷
     * @return
     */
    @Override
    public PageUtils showExam(PageInput input) {

        Page<QuestionMessage> page = new Page<>(input.getCurrPage(), input.getPageSize());
        // 查询数据
        QueryWrapper<QuestionMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(QuestionMessage::getState,1);
        Page<QuestionMessage> questionMessageList =
                questionMessageMapper.selectPage(page, queryWrapper);
        // 转换
        List<Message> messageList = new ArrayList<>();
        for (QuestionMessage questionMessage : questionMessageList.getRecords()) {
            // 出参对象
            Message message = new Message();
            message.setId(questionMessage.getId());
            message.setState(questionMessage.getState());
            message.setQuestionName(questionMessage.getQuestionName());
            messageList.add(message);
        }
        // 返回
        return new PageUtils(messageList,(int)questionMessageList.getTotal(), input.getPageSize(), input.getCurrPage());
    }

    /**
     * 查看成绩 管理员看全部非管理员看自己的
     *
     * @return
     */
    @Override
    public PageUtils showScore(PageInput input) {
        // 构建分页
        Page<ScoreEntity> page = new Page<>(input.getCurrPage(), input.getPageSize());
        // 当前登录用户
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        Long userId = principal.getUserId();
        QueryWrapper<ScoreEntity> scoreEntityQueryWrapper =
                new QueryWrapper<>();
        scoreEntityQueryWrapper.lambda().eq(ScoreEntity::getUserid,userId);
        if(ObjectUtil.isNotNull(input.getQuestionId())){
            scoreEntityQueryWrapper.lambda().eq(ScoreEntity::getQuestionId,input.getQuestionId());
        }
        Page<ScoreEntity> scoreEntityPage =
                scoreDao.selectPage(page, scoreEntityQueryWrapper);
        // 校验是否为系统管理员
        if (userId.equals(1L)) {
            QueryWrapper<ScoreEntity> wrapper = new QueryWrapper<>();
            if(ObjectUtil.isNotNull(input.getQuestionId())){
                wrapper.lambda().eq(ScoreEntity::getQuestionId,input.getQuestionId());
            }
            scoreEntityPage =  scoreDao.selectPage(page,wrapper);
        }
        List<Score> scores = new ArrayList<>();
        // 根据问卷id查名称 在进行添加
        for (ScoreEntity scoreEntity : scoreEntityPage.getRecords()) {
            Score score =new Score();
            QuestionMessage questionMessage =
                    questionMessageMapper.selectById(scoreEntity.getQuestionId());
            if(ObjectUtil.isNull(questionMessage)){
                throw new RuntimeException();
            }
            score.setScore(scoreEntity.getScore()).
                    setQuestionName(questionMessage.getQuestionName()).
                    setQuestionId(scoreEntity.getQuestionId()).
                    setCreatTime(scoreEntity.getCreatTime()).
                    setResponse(scoreEntity.getResponse()).
                    setUserid(scoreEntity.getUserid()).
                    setAnswerId(scoreEntity.getAnswerId()).
                    setNewScore(scoreEntity.getNewScore());
            if(ObjectUtil.isNull(scoreEntity.getNewScore())) score.setNewScore(0.0);
            scores.add(score);
        }
        return new PageUtils(scores,
                (int)scoreEntityPage.getTotal(),
                input.getPageSize(),
                input.getCurrPage());
    }
}
